package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.mapper.BlackUserMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.BlackUser;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UsersApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BlackUserService {

    @Autowired
    private BlackUserMapper blackUserMapper;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    //黑名单查询
    public IPage<BlackUser> queryBlackList(Integer page, Integer pageSize) {
        //获取当前用户
        User user = UserThreadLocal.get();
        //分页查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("created");
        //返回分页查询结果
        return blackUserMapper.selectPage(new Page<BlackUser>(page, pageSize), queryWrapper);
    }

    //取消黑名单
    public int blackListRemove(String id) {
        //获取当前登录用户的id
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        BlackUser blackUser = blackUserMapper.selectById(id);
        //黑名单用户在user表的id
        String blackUserId = blackUser.getBlackUserId();
        //添加好友关系
        usersApi.saveUsers(userId,Long.valueOf(blackUserId));
        //添加环信好友
        huanXinApi.addUserFriend(userId,Long.valueOf(blackUserId));
        //从黑名单表中删除用户
        return blackUserMapper.deleteById(id);
    }

    //读取全部黑名单用户id
    public List<Long> queryAllBlackUser(){
        QueryWrapper<BlackUser> wrapper = new QueryWrapper<>();
        List<BlackUser> blackUsers = blackUserMapper.selectList(wrapper);
        //新建存放id的集合
        List<Long> blackUsersId = new ArrayList<>();
        //循环存入
        for (BlackUser blackUser : blackUsers) {
            blackUsersId.add(Long.valueOf(blackUser.getBlackUserId()));
        }
        //返回集合
        return blackUsersId;
    }
}
